// 通过mutations间接更新state的多个方法的对象
import {
    reqAddress, 
    reqShops,
    reqUserInfo,
    reqLogout,
    reqShopInfo,
    reqShopRatings,
    reqShopGoods,
    reqSearchShops
} from '../api' 
import {
    RECEIVE_ADDRESS,
    RECEIVE_SHOPS,
    RECEIVE_USER_INFO,
    RESET_USER_INFO,
    RECEIVE_INFO,
    RECEIVE_RATINGS,
    RECEIVE_GOODS,
    INCREMENT_FOOD_COUNT,
    DECREMENT_FOOD_COUNT,
    CLEAR_CART,
    RECEIVE_SEARCH_SHOPS
} from './mutation-types' 
export default { 
    // 异步获取地址 
     async getAddress({commit, state}) { 
         //发送异步ajax请求
         const geohash = state.latitude + ',' + state.longitude 
         const result = await reqAddress(geohash) 
         const address = result.data
         commit(RECEIVE_ADDRESS, { address}) 
        },
    // 异步获取商家列表 
    async getShops({commit, state}) { 
        const {latitude, longitude} = state 
        const result = await reqShops({latitude, longitude}) 
        const shops = result.data
        commit(RECEIVE_SHOPS, {shops}) 
    },
    // 同步记录用户信息
    recordUser({commit},userInfo){
        commit(RECEIVE_USER_INFO, {userInfo}) 
    },
    // 异步获取用户信息 
    async getUserInfo({commit}) { 
        const result = await reqUserInfo() 
        commit(RECEIVE_USER_INFO, {
            userInfo: result.data
        }) 
        
    },
    // 异步退出
    async logout({commit}){
        const result = await reqLogout() 
        if(result.status === 1){
            commit(RESET_USER_INFO) 
        }
        
    },
    // 异步获取商家信息 
    async getShopInfo({commit}) { 
        const result = await reqShopInfo() 
        const info = result.data.data
        commit(RECEIVE_INFO, {info})     
        },
    // 异步获取商家评价列表 
    async getShopRatings({commit},callback) {
        const result = await reqShopRatings() 
        const ratings = result.data.data 
        commit(RECEIVE_RATINGS, {ratings}) 
        callback && callback();
    },
    // 异步获取商家商品列表 
    async getShopGoods({commit},callback) { 
        const result = await reqShopGoods() 
        const goods = result.data 
        commit(RECEIVE_GOODS, {goods}) 
        // 如果组件中传递了接收消息的回调函数, 数据更新后, 调用回调通知调用的组件 
        callback && callback();
    },
    // 更新指定 food 的 count 
    updateCount({commit}, {food, isAdd}) { 
        if(isAdd) { // 增加 
            commit(INCREMENT_FOOD_COUNT, {food}) } 
            else { // 减少 
                commit(DECREMENT_FOOD_COUNT, {food}) 
            } 
        },
    // 清空购物车 
    clearCart ({commit}) { commit(CLEAR_CART) },
    // 异步搜索商家列表 
    async searchShop({commit, state},keyword) { 
        const geohash = state.latitude + ',' + state.longitude 
        const result = await reqSearchShops({geohash,keyword}) 
        const searchShops = result.data
        commit(RECEIVE_SEARCH_SHOPS, {searchShops}) 
    },
     
    
}